<?php

!defined('IN_NOVA') && exit('Access Denied!');

class Ajax {

	public function start() {
		global $theme,$cache,$request;
		// 参数处理
		$action = $request->get( 'p' );

		@header("content-type: text/html; charset=utf-8");

		switch( $action )
		{
			case 'checkname':
				$this->check_name();
				break;
			case 'addcomment':
				$this->add_comment();
				break;
			default:
				echo '非法操作!|$|False';
		}
	}

	private function check_name()
	{
		global $db,$request,$user;
		$user_name = php_unescape( $request->get( 'username' ) );
		if( !$user->check_username( $user_name ) ) {
			echo '此用户名被禁止使用！|$|False';
			return -1;
		}
		if( $db->result( "SELECT COUNT(u_id) FROM `" . DB_PREFIX . "user` WHERE u_username='$user_name'" )) {
			echo '此用户名已经被注册！|$|False';
			return -2;
		} else {
			echo '用户名可以使用！|$|True';
			return 1;
		}
	}
	
	function add_comment(){
		global $db,$cache,$user,$theme,$request;
		// 预先检查
		if( $cache->config['comment'] == 2 ){
			echo '错误：管理员关闭了评论功能！|$|False';
			return -1;
		}
		if( $cache->config['comment'] == 1 && !user_is_login() ){
			echo '错误：只有注册会员才能评论，请先注册或登录！|$|False';
			return -2;
		}
		//If( CDate( DateDiff( "s", Session("PostDate"), Now() ) ) < CDate( Blogcomtimer ) ){
		//	echo "错误：请等一会儿再发表评论！|$|False";
		//	return -3;
		//}
		// 检查验证码
		//$vdcode = $request->get( 'vcode', 'P' );
		//if( ( $cache->config['verify'] == 0 || ( $cache->config['verify'] == 1 && !$user->is_login() ) ) && !check_verify( $vdcode ) ){
		//	echo '错误：验证码不正确!|$|False';
		//	return -4;
		//}
		// 获取数据
		if( $user->is_login() ){
			$user_name = $user->username;
			$temp = array();
			$temp = $db->fetch_one_array( "SELECT `u_email`,`u_index` FROM `" . DB_PREFIX . "user` WHERE u_username='$user_name'" );
			if( $temp['u_email'] != NULL ){
				$email = $temp['u_email'];
			}else{
				$email = '';
			}
			if( $temp['u_index'] != NULL ){
				$index = $temp['u_index'];
			}else{
				$index = '';
			}
			unset( $temp );
		}else{
			$user_name = trim( php_unescape( $request->get( 'username', 'P' ) ) );
			$email = htmlspecialchars( php_unescape( $request->get( 'email', 'P' ) ) );
			$index = htmlspecialchars( php_unescape( $request->get( 'index', 'P' ) ) );
			$check_name = $user->check_username( $user_name );
			if ( $check_name == 0 ) {
				echo "用户名长度必须在3-20字节之间。|$|False";
				return -5;
			} elseif ( $check_name == -1 ) {
				echo "用户名中含有非法字符。|$|False";
				return -6;
			} elseif ( $check_name == -2 ) {
				echo "用户名中含有系统禁用关键字。|$|False";
				return -7;
			} elseif ( $db->result( "SELECT COUNT(u_id) FROM `" . DB_PREFIX . "user` WHERE u_username = '" . $user_name . "'" ) ) {
				// 即使用户已经移入回收站，在彻底删除之前亦不能注册
				echo "该用户名已被注册。|$|False";
				return -8;
			}
			if ( empty( $email ) ) {
				//echo '请输入你的邮箱地址。|$|False';
				//return -9;
			} elseif ( !$user->check_email( $email ) ) {
				echo "你输入的邮箱地址格式有误！|$|False";
				return -10;
			} elseif ( $db->result( "SELECT COUNT(u_id) FROM `" . DB_PREFIX . "user` WHERE u_email='$email|" . strtolower( md5( $email ) ) . "'" ) ) {
				echo "您输入的邮箱地址已被注册！|$|False";
				return -11;
			}
			// 检查主页
			if ( empty( $index ) ) {
				//echo '请输入你的主页。';
				//return -12;
			} elseif ( !$user->check_index( $index ) ) {
				echo "你输入的主页地址格式有误！（最后不要加斜杠）|$|False";
				return -13;
			}
			$remember = $request->get( 'remember', 'P' );
			$blog_path = str_replace( ' ','%20', APP_PATH );
			if( $remember == 'on' ){
				setcookie( APP_PREFIX . 'username', $user_name, PHP_TIME + 31536000,$blog_path );
				setcookie( APP_PREFIX . 'email', $email, PHP_TIME + 31536000, $blog_path );
				setcookie( APP_PREFIX . 'index', $index, PHP_TIME + 31536000, $blog_path );
				setcookie( APP_PREFIX . 'remember', '1', PHP_TIME + 31536000, $blog_path );
			} else {
				setcookie( APP_PREFIX . 'username', NULL, 0,$blog_path );
				setcookie( APP_PREFIX . 'email', NULL, 0, $blog_path );
				setcookie( APP_PREFIX . 'index', NULL, 0, $blog_path );
				setcookie( APP_PREFIX . 'remember', NULL, 0, $blog_path );
			}
			if( $email != '' ) $email = $email . '|' . strtolower( md5( $email ) );
		}
		// 获取数据
		$comment = htmlspecialchars( $request->get( 'comment', 'P' ), ENT_QUOTES, 'UTF-8' );
		$comment = str_replace( array("\r\n", "\n", "\r"),'<br />',$comment);
		$article_id = $request->get( 'aid', 'P', 'int' );
		$hide = $request->get( 'hide', 'P' );
		// 检查数据
		if( trim( $comment ) == '' ){
			echo '错误：请输入内容！|$|False';
			return -14;
		}
		if( strlen( $comment ) > $cache->config['commaxlength'] ){
			echo '错误：您最多只能输入' . $cache->config['commaxlength'] . '字节的内容！|$|False';
			return -15;
		}
		// 处理 @ 回复
		$pattern = "/{@[1-9]\d*}/";
		$matches = $id_arr = array();
		if( preg_match_all ( $pattern, $comment, $matches ) ) {
			foreach( $matches[0] as $match ) {
				$id_arr[] = str_replace( array( '{@', '}' ), '', $match );
			}
			unset( $matches );
			include nova_lib( 'phpmailer' );
			$mail = new PHPMailer();
			foreach( $id_arr as $comment_id ) {
				// 处理每一个 @ 回复
				$respond = $db->fetch_one_array( "SELECT author,email FROM `" . DB_PREFIX . "comment` WHERE cid=$comment_id" );
				// 如果 cid 对应的评论不存在
				if( !$respond ) continue;
				// 替换 {@**}
				$comment = str_replace( '{@' . $comment_id . '}', '<a href="#comment-' . $comment_id . '">@ ' . $respond['author'] . '</a>', $comment );
				// 给每一个 @ 寄送邮件
				if( !$respond['email'] || 0 /* 全局开关待添加 */ ) continue;
				
			}
			unset( $respond, $mail );
		}
		// 写入数据库并检查关键词过滤
		$temp = true;
		$db->query( "INSERT INTO `" . DB_PREFIX . "comment` (`articleid`,`author`,`time`,`comment`,`email`,`index`,`isshow`) VALUES ($article_id,'$user_name','" . PHP_TIME . "','$comment','$email','$index',1)" );
		$cid = $db->insert_id();
		$filter_arr = split( "\|", $cache->config['filterwords'] );
		if ( count( $filter_arr ) ) {
			foreach( $filter_arr as $filter_word ){
				if ( empty( $filter_word ) ) continue;
				if( !( stripos($comment,$filter_word) === false ) ){
					$db->query( "UPDATE `" . DB_PREFIX . "comment` SET isshow = 0 WHERE `cid` = $cid" );
					$temp = false;
					break;
				}
			}
		}
		// 如果是一句悄悄话
		if( $hide == 'on' ) $db->query( "UPDATE `" . DB_PREFIX . "comment` SET isshow = 2 WHERE cid=$cid" );
		// 输出 ajax 内容
		$theme->comment = $db->fetch_one_array( "SELECT * FROM `" . DB_PREFIX . "comment` WHERE cid=$cid" );
		if( $db->result( "SELECT type FROM `" . DB_PREFIX . "article` WHERE id=$article_id" ) == '静态' ){
			$theme->comment['comment'] .= '<br /><font color="red">[此评论需要静态页刷新后才能显示]</font>';
			$db->query( "UPDATE `" . DB_PREFIX . "article` SET `update`=1 WHERE id=$article_id" );
		}else{
			if( $temp != false ){
				$theme->comment['comment'] .= '<br /><font color="blue">[您的评论已经成功发表]</font>';
			}
		}
		if( $article_id != 0 ){
			$db->query( "UPDATE `" . DB_PREFIX . "article` SET comment = comment + 1 WHERE id = $article_id" );
		}
		$theme->show_comment_de();
		echo '|$|True';
		// 更新缓存
		if( $article_id == 0 ) {
			$cache->refresh( 'guestbook_new', TRUE );
		}else{
			$cache->refresh( 'comment_new', TRUE );
		}
		$cache->refresh( 'count', TRUE );
	}

}
?>
